package games.gong.durid.service.impl;

import games.gong.durid.entity.Permission;
import games.gong.durid.entity.Role;
import games.gong.durid.mapper.RoleMapper;
import games.gong.durid.mapper.RolePermissionMapper;
import games.gong.durid.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Override
    public int addRole(Role role) {
        // 忽略客户端传递的时间字段，由服务端生成
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        int result = roleMapper.insert(role);
        return result;
    }
    
    @Override
    public int deleteRole(Long id) {
        // 先删除角色权限关联数据
        rolePermissionMapper.deleteByRoleIdAndPermissionId(id, null);
        // 再删除角色
        int result = roleMapper.deleteById(id);
        return result;
    }
    
    @Override
    public int updateRole(Role role) {
        // 忽略客户端传递的时间字段，由服务端生成
        role.setUpdateTime(LocalDateTime.now());
        int result = roleMapper.update(role);
        return result;
    }
    
    @Override
    public Role getRoleById(Long id) {
        Role role = roleMapper.selectById(id);
        return role;
    }
    
    @Override
    public List<Role> getAllRoles() {
        List<Role> roles = roleMapper.selectAll();
        return roles;
    }
    
    @Override
    public List<Role> getRolesByUserId(Long userId) {
        return roleMapper.selectRolesByUserId(userId);
    }
    
    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        return roleMapper.selectPermissionsByRoleId(roleId);
    }
}